package com.safe.app.config.context;


import com.safe.app.model.User;

import java.util.HashMap;
import java.util.Map;

/**
 * 用于在应用内传递上下文信息。
 *
 * @author h2l
 */
public class ExecutionContext {

    static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static final String USER_ID = "user_id";
    public static final String LOGIN_USER = "login_user";

    public static void setUserId(String userId) {
        put(USER_ID, userId);
    }

    public static String getUserId() {
        return (String) get(USER_ID);
    }

    public static void setLoginUser(User sysUser) {
        put(LOGIN_USER, sysUser);
    }

    public static User getLoginUser() {
        return (User) get(LOGIN_USER);
    }

    public static Object put(String key, Object value) {
        Map<String, Object> contextMap = getContextMap();
        if (contextMap == null) {
            contextMap = new HashMap<>();
            setContextMap(contextMap);
        }
        return contextMap.put(key, value);
    }

    public static Map<String, Object> getContextMap() {
        return threadLocal.get();
    }

    public static void setContextMap(Map<String, Object> contextMap) {
        threadLocal.set(contextMap);
    }

    /**
     * 获取键下的值.如果不存在，返回null；如果名值Map未初始化，也返回null
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        Map<String, Object> contextMap = getContextMap();
        if (contextMap == null) {
            return null;
        }
        return contextMap.get(key);
    }

}
